﻿using System;
using System.Data.Linq;
using System.Linq;
using System.Text;
using eCommerce.DataAccess;

namespace eCommerce.BusinessLogic
{
    public class OrderBL
    {
        public static string GetCardName(int cardTypeId)
        {
            return OrderDA.GetCardName(cardTypeId);
        }
        public static string GetOrderRefNum(Guid cartId)
        {
            return OrderDA.GetOrderRefNum(cartId);
        }

        public static string GetCardValue(int cardtypeId)
        {
            return OrderDA.GetCardValue(cardtypeId);
        }
        public static int CardTypeId(string cardType)
        {
            return OrderDA.CardTypeId(cardType);
        }


        public static Address GetDeliveryAddress(Guid deliveryaddressId)
        {
            return OrderDA.GetDeliveryAddress(deliveryaddressId);
        }

        public static Country_Code GetCountryCodes(int countryCodeId)
        {
            return OrderDA.GetCountryCodes(countryCodeId);
        }

        public static Address GetBillingAddress(Guid billingAddressId)
        {
            return OrderDA.GetBillingAddress(billingAddressId);
        }

        public static CustomerCard GetCardDetails(Guid userId)
        {
            return OrderDA.GetCardDetails(userId);
        }
        public static Order GetOrderDetails(Guid userId)
        {
            return OrderDA.GetOrderDetails(userId);
        }
        
        public static IQueryable<decimal?> GetCartPrice(Guid cartId)
        {
            return OrderDA.GetCartPrice(cartId);
        }

        public static ISingleResult<getCardTypeResult> GetCardType()
        {
            return OrderDA.GetCardType();
        }

        /// <summary>
        /// Encodes the card.
        /// </summary>
        /// <param name="toEncode">To encode.</param>
        /// <returns></returns>
        static public string EncodeCard(string toEncode)
        {
            var encodedcard = Convert.ToBase64String(Encoding.UTF8.GetBytes(toEncode));
            return encodedcard;
        }

        /// <summary>
        /// Decodes the card.
        /// </summary>
        /// <param name="toDecode">To decode.</param>
        /// <returns></returns>
        static public string DecodeCard(string toDecode)
        {
            byte[] toDecodeByte = Convert.FromBase64String(toDecode);

            UTF8Encoding encoder = new UTF8Encoding();
            Decoder utf8Decode = encoder.GetDecoder();

            int charCount = utf8Decode.GetCharCount(toDecodeByte, 0, toDecodeByte.Length);

            char[] decodedChar = new char[charCount];
            utf8Decode.GetChars(toDecodeByte, 0, toDecodeByte.Length, decodedChar, 0);
            string decodedcard = new String(decodedChar);
            return decodedcard;
        }

        /// <summary>
        /// Inserts the customer payment details
        /// </summary>
        /// <param name="currentUid"></param>
        /// <param name="cardTypeId"></param>
        /// <param name="cardHolderName"></param>
        /// <param name="encodedCardNumber"></param>
        /// <param name="expiryDate"></param>
        /// <param name="startDate"></param>
        /// <param name="issueNumber"></param>
        /// <param name="CV2"></param>
        public static void InsertCustomerPaymentDetails(Guid currentUid, int cardTypeId, string cardHolderName, string encodedCardNumber, string expiryDate, string  startDate, string issueNumber, string CV2)
        {
            CustomerCard customerCard = new CustomerCard
                                            {
                                                userID = currentUid,
                                                CardTypeID = cardTypeId,
                                                CardName = cardHolderName,
                                                CardNum = encodedCardNumber,
                                                ExpiryDate = expiryDate
                                            };

            if (startDate != "")
            {
                customerCard.StartDate = startDate;
            }
            else
            {
                customerCard.IssueNo = Convert.ToInt32(issueNumber);
            }
            customerCard.CVV = Convert.ToInt32(CV2);

            // Save to the DB
            OrderDA.InsertCustomerPaymentDetails(customerCard);

        }
       
        /// <summary>
        /// Updates the customer payment details
        /// </summary>
        /// <param name="card"></param>
        /// <param name="currentUid"></param>
        /// <param name="cardTypeId"></param>
        /// <param name="cardHolderName"></param>
        /// <param name="encodedCardNumber"></param>
        /// <param name="expiryDate"></param>
        /// <param name="startDate"></param>
        /// <param name="issueNumber"></param>
        /// <param name="CV2"></param>
        public static void UpdateCustomerPaymentDetails(CustomerCard card,Guid currentUid,int cardTypeId, string cardHolderName, string encodedCardNumber, string expiryDate, string startDate, string issueNumber, string CV2)
        {
            card.CardTypeID = cardTypeId;
            card.CardName = cardHolderName;
            card.ExpiryDate = expiryDate;
            if (issueNumber != "")
            {
                card.IssueNo = Convert.ToInt32(issueNumber);
            }
           
            card.CardNum = encodedCardNumber;
            card.CVV = Convert.ToInt32(CV2);
            card.StartDate = startDate;
            card.userID = currentUid;

            OrderDA.UpdateCustomerPaymentDetails(card);
        }
       
       public static void InsertOrderDetails(Guid orderid,Guid cartid, Guid currentUid, int orderstatus, DateTime ordercreated, Guid deliveryaddressid, Guid billingaddressid, Decimal ordertototalmoney, int orderpaymenttype, string vatnumber, int discount)
        {
            Order order = new Order
            {
                OrderID = orderid,
                cartid = cartid,
                customerid = currentUid,
                orderstatus = orderstatus,
                ordercreated = ordercreated,
                shippingaddressid = deliveryaddressid,
                billingaddressid = billingaddressid,
                //orderref = orderref,
                ordertotalmoney = ordertototalmoney,
                orderpaymenttype = orderpaymenttype,
                vatnumber = vatnumber,
                discount = discount
            };

            // Save to the DB
            OrderDA.InsertOrderDetails(order);
        }
       public static void UpdateOrderDetails(Order order, Guid cartid, Guid currentUid, int orderstatus, Guid deliveryaddressid, Guid billingaddressid, Decimal ordertototalmoney, string vatnumber, int discount)
       {
           order.cartid = cartid;
           order.customerid = currentUid;
           order.orderstatus = orderstatus;
           //order.ordercreated = ordercreated;  // Dont need this - automatic date
           order.shippingaddressid = deliveryaddressid;
           order.billingaddressid = billingaddressid;
           //order.orderref = orderref;
           order.ordertotalmoney = ordertototalmoney;
           //order.orderpaymenttype = orderpaymenttype;   //Not using this eg:(Card/Cheque/Wire Transfer)
           order.vatnumber = vatnumber;
           order.discount = discount;

           OrderDA.UpdateOrderDetails(order);
       }
        public static void InsertOrderProductDetails(Guid orderId, int productId, string productType, int quantity, DateTime dateCreated, int stutus)
        {
            OrderDetail orderDetail = new OrderDetail
                                          {
                                              orderid = orderId,
                                              productid = productId,
                                              producttype = productType,
                                              quantity = quantity,
                                              datecreated = dateCreated,
                                              status = stutus,
                                          };
            OrderDA.InsertOrderProductDetails(orderDetail);
       }
     
        public static void UpdateOrderStatus(Guid cartId, int orderstatus)
        {
            OrderDA.UpdateOrderStatus(cartId, orderstatus);
        }
        public static void UpdateOrderProductsStatus(Guid orderId, int orderstatus)
        {
            OrderDA.UpdateOrderProductsStatus(orderId, orderstatus);
        }

        static public int GetRandonNumber()
        {
            int number = new Random().Next(100000, 999999);
            
            if (OrderDA.CheckRandonNumber(number) != null)
            {
                number = new Random().Next(100000, 999999);
                return number;
            }
            return number;
        }
        static public decimal GetTotalCartPrice(Guid cartId)
        {
            decimal total = 0;
            var cartPrices = GetCartPrice(cartId);

            foreach (var price in cartPrices)
            {
                total = total + price.Value;
            }
            return total;
        }
        public static void InsertCartProduct(Guid cartId, int productId, int qty, int productType, DateTime dateTime, decimal price)
         {
            Cart_Product cartProduct = new Cart_Product
                                           {
                                               cartid = cartId,
                                               productid = productId,
                                               qty = qty,
                                               producttype = productType,
                                               datetime = dateTime,
                                               price = price
                                           };
            OrderDA.InsertCartProduct(cartProduct);
         }

        public static void UpdateCartProduct(Cart_Product cartProduct, Guid cartId, int productId, int qty, int productType, DateTime dateTime, decimal price)
        {
            cartProduct.cartid = cartId;
            cartProduct.productid = productId;
            cartProduct.qty = qty;
            cartProduct.producttype = productType;
            cartProduct.datetime = dateTime;
            cartProduct.price = price;
            OrderDA.UpdateCartProduct(cartProduct);
            
        }
         public static decimal GetProductPrice(Int32 itemId)
        {
            return OrderDA.GetProductPrice(itemId);
        }
         public static int GetProductType(Int32 itemId)
        {
             return OrderDA.GetProductType(itemId);
        }
        public static bool CheckProductCart(Guid cartId, int itemId)
        {
            return OrderDA.CheckProductCart(cartId, itemId);
        }
        public static Cart_Product GetProductCart(Guid cartId, int itemId)
        {
            return OrderDA.GetProductCart(cartId, itemId);
        }
        public static int GetProductCartQty(Guid cartId, int itemId)
        {
            return OrderDA.GetProductCartQty(cartId, itemId);
        }
        public static Product GetProduct(int itemId)
        {
            return OrderDA.GetProduct(itemId);
        }
        public static ISingleResult<getProductbyCategoryResult> GetProductByCategory(int _item)
        {
            return OrderDA.GetProductByCategory(_item);
        }
    }
}
